import Color from "@/utils/Color"
import Bucket from "./Bucket"
import { strokeRect, fillText } from "@/utils/common"
export default class Square {
  constructor(key, value, x, y, flag, algorithmIndex = 7, width = 45, height = 30) {
    this.key = key
    this.value = value
    this.x = x
    this.y = y
    this.flag = flag
    this.width = width
    this.height = height

    Square.minValue = Math.min(Square.minValue, value)
    Square.maxValue = Math.max(Square.maxValue, value)
    Square.algorithmIndex = algorithmIndex
  }

  static init(arrLen) {
    Square.minValue = 10000
    Square.maxValue = -1
    Square.buckets = []
    Square.algorithmIndex = 7
    Square.arrLen = arrLen
    Square.curLen = 0

    let clientWidth = document.getElementById('canvas-container').clientWidth
    Square.startX = clientWidth / 2 - ((Square.arrLen > 15 ? 14 : Square.arrLen - 1) * 55 + 45) / 2

    Square.startY = document.getElementById('canvas-container').clientHeight - 75
  }


  draw(ctx) {
    ctx.beginPath()
    ctx.fillStyle = 'black'
    strokeRect(ctx, this.x, this.y, this.width, this.height)
    let value = this.value
    for (let i = 2; i >= 0; i--) {
      let r = value % 10
      if (this.flag === 5) {
        ctx.fillStyle = 'green'
      } else if (this.flag === 4) {
        ctx.fillStyle = Color.ORANGE
      } else if (this.flag === 2 - i + 1) {
        ctx.fillStyle = 'red'
      } else {
        ctx.fillStyle = 'black'
      }
      fillText(ctx, r, this.x + 15 * i + 7.5, this.y + 15)
      value = Math.floor(value / 10)
    }

    Square.curLen ++

    if (Square.curLen === Square.arrLen) {
      Square.drawBuckets(ctx)
      Square.curLen = 0
    }
  }


  static createBuckets() {

    let clientWidth = document.getElementById('canvas-container').clientWidth

    let clientHeight = document.getElementById('canvas-container').clientHeight

    let startX = clientWidth / 2 - (55 * 9 + 45) / 2


    for (let i = 0; i < 10; i++) {
      if (Square.algorithmIndex === 8) {
        let span = Math.floor((Square.maxValue - Square.minValue) / 9)
        let left = Square.minValue + span * i
        let right = left + span
        startX = clientWidth / 2 - (110 * 9 + 55) / 2
        Square.buckets[i] = new Bucket(startX + 110 * i, clientHeight - 40, '[' + left + ',' + right + ')')
      } else {
        Square.buckets[i] = new Bucket(startX + 55 * i, clientHeight - 40, i)
      }
    }

  }

  static drawBuckets(ctx) {
    Square.buckets.forEach(b => b.draw(ctx))
  }

  deepCopy() {
    return new Square(this.key, this.value, this.x, this.y, this.flag, this.algorithmIndex, this.width, this.height)
  }

  static setFlags(arr, flag) {
    arr.forEach(s => s.flag = flag)
  }
}